const axios = require('axios')
const formatDate = require('../../lib/formatDate')
const crypto = require('crypto')
const logger = require('log4js').getLogger()

const app_key = 'eb2ba389f71b4883a0beb0ac9dd637d6'
const app_secret = '90df1ed428cb448f95befd41150ddf31'
const format = 'json'
const v = '1.0'
const sign_method = 'md5'
const _url = 'https://router.jd.com/api?'

const jd = {
    union: {
        open: {
            
            goods: {
                promotiongoodsinfo: {
                    query(skuIds) {
                        var obj = {
                            // access_token: '',
                            app_key: app_key,
                            format: format,
                            method: 'jd.union.open.goods.promotiongoodsinfo.query',
                            param_json: JSON.stringify({
                                skuIds: skuIds + ''
                            }),
                            sign_method: sign_method,
                            timestamp: formatDate(new Date()),
                            v: v
                        }
                        var str = ''
                        for (var key in obj)
                            str += key + obj[key]
                        str = app_secret + str + app_secret
                        var sign = crypto.createHash("md5").update(str).digest("hex").toUpperCase()
                        var url = _url + 'sign=' + sign
                        for (var key in obj)
                            url += '&' + key + '=' + obj[key]
                        return new Promise((resolve, reject) => {
                            axios.get(url).then(response => {
                                var result = response.data
                                if (result.jd_union_open_goods_promotiongoodsinfo_query_response &&
                                    result.jd_union_open_goods_promotiongoodsinfo_query_response.code == "0" &&
                                    result.jd_union_open_goods_promotiongoodsinfo_query_response.result) {
                                    result = JSON.parse(result.jd_union_open_goods_promotiongoodsinfo_query_response.result)
                                    if (result.code == 200) {
                                        result.data = result.data || []
                                        resolve(result.data)
                                        return
                                    }
                                }
                                logger.error('[' + __filename + ':' + __line + ']', JSON.stringify(response.data))
                                reject()
                            }, result => {
                                if (result)
                                    logger.error('[' + __filename + ':' + __line + ']', result)
                                reject()
                            })
                        })
                    }
                }
            },
            order: {
                query(time, type, pageNo) {
                    pageNo = pageNo || 1
                    type = type || 1
                    var obj = {
                        // access_token: '',
                        app_key: app_key,
                        format: format,
                        method: 'jd.union.open.order.query',
                        param_json: JSON.stringify({
                            orderReq: {
                                pageNo: pageNo,
                                pageSize: 500,
                                type: type,
                                time: time
                            }
                        }),
                        sign_method: sign_method,
                        timestamp: formatDate(new Date()),
                        v: v
                    }
                    var str = ''
                    for (var key in obj)
                        str += key + obj[key]
                    str = app_secret + str + app_secret
                    var sign = crypto.createHash("md5").update(str).digest("hex").toUpperCase()
                    var url = _url + 'sign=' + sign
                    for (var key in obj)
                        url += '&' + key + '=' + obj[key]
                    return new Promise((resolve, reject) => {
                        axios.get(url).then(response => {
                            var result = response.data
                            if (result.jd_union_open_order_query_response &&
                                result.jd_union_open_order_query_response.code == "0" &&
                                result.jd_union_open_order_query_response.result) {
                                result = JSON.parse(result.jd_union_open_order_query_response.result)
                                if (result.code == 200) {
                                    result.data = result.data || []
                                    new Promise((resolve, reject) => {
                                        if (result.hasMore) {
                                            jd.union.open.order.query(time, type, pageNo + 1).then(_result => {
                                                result.data.push.apply(result.data, _result)
                                                resolve()
                                            }, result => {
                                                if (result)
                                                    logger.error('[' + __filename + ':' + __line + ']', result)
                                                reject()
                                            })
                                            return
                                        }
                                        resolve()
                                    }).then(() => {
                                        if (type < 3) {
                                            jd.union.open.order.query(time, type + 1).then(_result => {
                                                _result.forEach(item => {
                                                    let i = 0
                                                    for (; i < result.data.length; ++i) {
                                                        if (result.data[i].orderId == item.orderId) {
                                                            break
                                                        }
                                                    }
                                                    if (i == result.data.length) {
                                                        result.data.push(item)
                                                    }
                                                })
                                                resolve(result.data)
                                            }, result => {
                                                if (result)
                                                    logger.error('[' + __filename + ':' + __line + ']', result)
                                                reject()
                                            })
                                            return
                                        }
                                        resolve(result.data)
                                    }, result => {
                                        if (result)
                                            logger.error('[' + __filename + ':' + __line + ']', result)
                                        reject()
                                    })
                                    return
                                }
                            }
                            logger.error('[' + __filename + ':' + __line + ']', JSON.stringify(response.data))
                            reject()
                        }, result => {
                            if (result)
                                logger.error('[' + __filename + ':' + __line + ']', result)
                            reject()
                        })
                    })
                }
            },
            promotion: {
                common: {
                    get(link) {
                        if (link.indexOf('jd') == -1)
                            return Promise.reject()
                        if (link.indexOf('?') != -1)
                            link = link.substring(0, link.indexOf('?'))
                        var obj = {
                            // access_token: '',
                            app_key: app_key,
                            format: format,
                            method: 'jd.union.open.promotion.common.get',
                            param_json: JSON.stringify({
                                promotionCodeReq: {
                                    materialId: link,
                                    siteId: '1015309151'
                                }
                            }),
                            sign_method: sign_method,
                            timestamp: formatDate(new Date()),
                            v: v
                        }
                        var str = ''
                        for (var key in obj)
                            str += key + obj[key]
                        str = app_secret + str + app_secret
                        var sign = crypto.createHash("md5").update(str).digest("hex").toUpperCase()
                        var url = _url + 'sign=' + sign
                        for (var key in obj)
                            url += '&' + key + '=' + obj[key]
                        return new Promise((resolve, reject) => {
                            axios.get(url).then(response => {
                                var result = response.data
                                if (result.jd_union_open_promotion_common_get_response &&
                                    result.jd_union_open_promotion_common_get_response.code == "0" &&
                                    result.jd_union_open_promotion_common_get_response.result) {
                                    result = JSON.parse(result.jd_union_open_promotion_common_get_response.result)
                                    if (result.code == 200 && result.data && result.data.clickURL) {
                                        resolve(result.data.clickURL)
                                        return
                                    }
                                }
                                logger.error('[' + __filename + ':' + __line + ']', JSON.stringify(response.data))
                                reject()
                            }, result => {
                                if (result)
                                    logger.error('[' + __filename + ':' + __line + ']', result)
                                reject()
                            })
                        })
                    }
                }
            }
        }
    }
}

module.exports = jd